//
//  TransferRecord.m
//  RPay
//
//  Created by CharlieLiao on 2017/7/23.
//  Copyright © 2017年 Charlie. All rights reserved.
//

#import "TransferRecord.h"
#import "MJExtension.h"
#import "CLExtension/CLExtension.h"

@implementation TransferRecord

- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property
{
    if ([property.name isEqualToString:@"dealTime"]) {
        return [NSDate dateWithTimestamp:oldValue];
    }
    return oldValue;
}

@end

@implementation TransferRecordList

- (instancetype)init
{
    self = [super init];
    if (self) {
        _keys = @[];
        _content = @{};
    }
    return self;
}

- (void)setTotal:(NSUInteger)total
{
    if (_pageNo == 0)
        _total = total;
}

- (void)append:(NSArray<TransferRecord*>*)records
{
    NSMutableDictionary *contentDict;
    if (_pageNo == 0) {
        contentDict = [NSMutableDictionary dictionary];
        _count = records.count;
        
    } else {
        contentDict = [NSMutableDictionary dictionaryWithDictionary:_content];
        _count += records.count;
    }
    
    for (TransferRecord *record in records) {
        NSString *dateStr = [record.dealTime toString:@"yyyy-MM"];
        NSMutableArray *list = contentDict[dateStr];
        if (list == nil) {
            list = [NSMutableArray array];
            contentDict[dateStr] = list;
        }
        [list addObject:record];
    }
    
    _content = [NSDictionary dictionaryWithDictionary:contentDict];
    _keys = [_content.allKeys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:false]]];
    
    ///
    _isAll = _count >= _total;
}

@end

@implementation TransferRecordReformer

- (instancetype)init
{
    return [self initWithRecordList:[TransferRecordList new]];
}

- (instancetype)initWithRecordList:(TransferRecordList*)list
{
    self = [super init];
    if (self)
        _list = list;
    return self;
}

- (id)manager:(CTAPIBaseManager *)manager reformData:(id)data
{
    _list.total = [toSafeObject(data[@"total"]) integerValue];
    _list.amountIn = toSafeObject(data[@"amountIn"]);
    _list.amountOut = toSafeObject(data[@"amountOut"]);
    NSArray *records = [TransferRecord mj_objectArrayWithKeyValuesArray:toSafeObject(data[@"content"])];
    [_list append:records];
    return _list;
}

@end


